using System;
using System.Collections.Generic;
using System.Text;
using System.Workflow.Runtime.Tracking;

namespace OpenComposite.EII.Simulation
{
	public class SimulationTrackingService : TrackingService
	{
		#region Initialization
		public SimulationTrackingService() : base()
		{
			init();
		}
		private void init()
		{
			_profile = new SimulationTrackingProfile();		
		}
		#endregion

		#region Override: TrackingService
		protected override TrackingProfile GetProfile(Guid workflowInstanceId)
		{
			return _profile;
		}

		protected override TrackingProfile GetProfile(Type workflowType, Version profileVersionId)
		{
			return _profile;
		}

		protected override TrackingChannel GetTrackingChannel(TrackingParameters parameters)
		{
			SimulationTrackingChannel channel = new SimulationTrackingChannel(parameters);
			channel.Tracking += new EventHandler<SimulationTrackingEventArgs>(channel_Tracking);
			channel.CompletedOrTerminated += new EventHandler<SimulationTrackingEventArgs>(channel_CompletedOrTerminated);
			return channel;
		}

		protected override bool TryGetProfile(Type workflowType, out TrackingProfile profile)
		{
			profile = _profile;
			return true;
		}

		protected override bool TryReloadProfile(Type workflowType, Guid workflowInstanceId, out TrackingProfile profile)
		{
			profile = _profile;
			return true;
		}
		#endregion

		#region Public Members

		#region Events
		public event EventHandler<SimulationTrackingEventArgs> Tracking = null;
		public event EventHandler<SimulationTrackingEventArgs> CompletedOrTerminated = null;
		#endregion

		#endregion

		#region Private Members

		#region Variables
		private TrackingProfile _profile;
		#endregion

		#region Methods
		private void onTracking(object sender, SimulationTrackingEventArgs e)
		{
			EventHandler<SimulationTrackingEventArgs> tmp = this.Tracking;
			if ( tmp != null )
				tmp(sender, e);
		}
		private void onCompletedOrTerminated(object sender, SimulationTrackingEventArgs e)
		{
			SimulationTrackingChannel channel = sender as SimulationTrackingChannel;
			if ( channel != null ) {
				channel.Tracking -= new EventHandler<SimulationTrackingEventArgs>(channel_Tracking);
				channel.CompletedOrTerminated -= new EventHandler<SimulationTrackingEventArgs>(channel_CompletedOrTerminated);
			}

			EventHandler<SimulationTrackingEventArgs> tmp = this.CompletedOrTerminated;
			if ( tmp != null )
				tmp(sender, e);
		}
		#endregion

		#region Event Handlers
		private void channel_CompletedOrTerminated(object sender, SimulationTrackingEventArgs e)
		{
			onCompletedOrTerminated(sender, e);
		}

		private void channel_Tracking(object sender, SimulationTrackingEventArgs e)
		{
			onTracking(sender, e);
		}

		#endregion

		#endregion
	}
}
